import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class MemberLoginPage extends StatefulWidget {
  const MemberLoginPage({super.key, this.onConfirm});

  // 添加确认回调参数
  final void Function(String)? onConfirm;

  @override
  State<MemberLoginPage> createState() => _MemberLoginPageState();
}

class _MemberLoginPageState extends State<MemberLoginPage> {
  // 存储输入的数字
  String _inputValue = '';

  // 控制是否显示系统键盘
  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    // 监听文本变化
    _controller.addListener(() {
      setState(() {
        _inputValue = _controller.text;
      });
    });

    // 添加监听器处理键盘事件
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        // 当获得焦点时，添加回车监听
        _controller.addListener(_handleTextInput);
      } else {
        // 当失去焦点时，移除监听器
        _controller.removeListener(_handleTextInput);
        // 重新请求焦点，保持键盘始终可用
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            FocusScope.of(context).requestFocus(_focusNode);
          }
        });
      }
    });

    // 初始化时自动聚焦
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        FocusScope.of(context).requestFocus(_focusNode);
      }
    });
  }

  // 处理文本输入（包括回车）
  void _handleTextInput() {
    // 这里可以处理实时输入变化
  }

  @override
  void dispose() {
    _controller.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  // 处理数字输入
  void _handleNumberInput(String number) {
    setState(() {
      _inputValue += number;
      _controller.text = _inputValue;
      // 保持光标在末尾
      _controller.selection = TextSelection.fromPosition(
        TextPosition(offset: _controller.text.length),
      );
      // 确保焦点不丢失
      if (!_focusNode.hasFocus) {
        FocusScope.of(context).requestFocus(_focusNode);
      }
    });
  }

  // 处理删除
  void _handleDelete() {
    if (_inputValue.isNotEmpty) {
      setState(() {
        _inputValue = _inputValue.substring(0, _inputValue.length - 1);
        _controller.text = _inputValue;
        // 确保焦点不丢失
        if (!_focusNode.hasFocus) {
          FocusScope.of(context).requestFocus(_focusNode);
        }
      });
    }
  }

  // 处理确认（回车回调）
  void _handleConfirm() {
    // 执行传入的确认回调
    if (widget.onConfirm != null) {
      widget.onConfirm!(_inputValue);
    }

    // 确认后重新聚焦
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        FocusScope.of(context).requestFocus(_focusNode);
      }
    });
  }

  // 切换系统键盘显示
  void _toggleSystemKeyboard() {
    if (_focusNode.hasFocus) {
      _focusNode.unfocus();
    } else {
      FocusScope.of(context).requestFocus(_focusNode);
    }
  }

  // 数字键盘按钮
  Widget _buildNumberButton(String number) {
    return Expanded(
      child: Padding(
        padding: const EdgeInsets.all(4.0),
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(6),
            ),
            padding: const EdgeInsets.symmetric(vertical: 16),
            side: BorderSide(color: Colors.grey.shade300),
          ),
          onPressed: () => _handleNumberInput(number),
          child: Text(
            number,
            style: const TextStyle(
              fontSize: 22,
              color: Colors.black87,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ),
    );
  }

  // 微信支付样式键盘按钮（特殊样式）
  Widget _buildSpecialButton({required String text, required VoidCallback onPressed, Color? backgroundColor, Color? textColor}) {
    return Expanded(
      child: Padding(
        padding: const EdgeInsets.all(4.0),
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
            backgroundColor: backgroundColor ?? Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(6),
            ),
            padding: const EdgeInsets.symmetric(vertical: 16),
            side: BorderSide(color: Colors.grey.shade300),
          ),
          onPressed: onPressed,
          child: Text(
            text,
            style: const TextStyle(
              fontSize: 22,
              color: Colors.black87,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 340,
      height: 500,
      child: Column(
        children: [
          // 输入框区域
          Padding(
            padding: const EdgeInsets.all(12.0),
            child: Container(
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey),
                borderRadius: BorderRadius.circular(4),
              ),
              child: TextField(
                controller: _controller,
                focusNode: _focusNode,
                keyboardType: TextInputType.number,
                inputFormatters: [
                  FilteringTextInputFormatter.digitsOnly, // 只允许输入数字
                ],
                onSubmitted: (value) => _handleConfirm(),
                // 添加回车提交回调
                decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: '请输入手机号',

                  suffixIcon: IconButton(
                    icon: Icon(_focusNode.hasFocus ? Icons.keyboard_hide : Icons.keyboard),
                    onPressed: _toggleSystemKeyboard,
                  ),
                ),
                textAlign: TextAlign.center,
              ),
            ),
          ),

          // 自定义数字键盘（微信支付样式）
          Expanded(
            child: Padding(
              padding: const EdgeInsets.all(10.0),
              child: Column(
                children: [
                  // 第一行：1 2 3
                  Row(
                    children: [
                      _buildNumberButton('1'),
                      _buildNumberButton('2'),
                      _buildNumberButton('3'),
                    ],
                  ),
                  // 第二行：4 5 6
                  Row(
                    children: [
                      _buildNumberButton('4'),
                      _buildNumberButton('5'),
                      _buildNumberButton('6'),
                    ],
                  ),
                  // 第三行：7 8 9
                  Row(
                    children: [
                      _buildNumberButton('7'),
                      _buildNumberButton('8'),
                      _buildNumberButton('9'),
                    ],
                  ),
                  // 第四行：. 0 删除
                  Row(
                    children: [
                      _buildSpecialButton(
                        text: '',
                        onPressed: () => null,
                        // backgroundColor: Colors.grey.shade50,
                      ),
                      _buildNumberButton('0'),
                      _buildSpecialButton(
                        text: '删除',
                        onPressed: _handleDelete,
                        backgroundColor: Colors.grey.shade50,
                        textColor: Colors.black87,
                      ),
                    ],
                  ),
                  // 第五行：确认按钮
                  Row(
                    children: [
                      _buildSpecialButton(
                        text: '确认',
                        onPressed: _handleConfirm,
                        backgroundColor: Colors.green,
                        textColor: Colors.white,
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
